import * as echarts from 'echarts'

// 定义图表事件类型
export const ChartEventType = {
  REGION_SELECT: 'regionSelect',
  TIME_RANGE_CHANGE: 'timeRangeChange'
}

export function initTradeChart(el) {
  const chart = echarts.init(el)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      }
    },
    series: [
      {
        name: '交易额',
        type: 'bar',
        data: [320, 332, 301, 334, 390, 330, 320, 332, 301, 334, 390, 330],
        itemStyle: {
          color: '#2f89cf'
        }
      }
    ]
  }
  chart.setOption(option)
  return chart
}

export function initMemberChart(el) {
  const chart = echarts.init(el)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      }
    },
    series: [
      {
        name: '会员数',
        type: 'line',
        data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330],
        smooth: true,
        itemStyle: {
          color: '#00f2f1'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(0,242,241,0.3)'
            }, {
              offset: 0.8,
              color: 'rgba(0,242,241,0)'
            }],
            global: false
          }
        }
      }
    ]
  }
  chart.setOption(option)
  return chart
}

export function initMapChart(el) {
  const chart = echarts.init(el)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}'
    },
    visualMap: {
      min: 0,
      max: 1000,
      left: 'left',
      top: 'bottom',
      text: ['高', '低'],
      calculable: true,
      inRange: {
        color: ['#1f78b4', '#b2182b']
      },
      textStyle: {
        color: '#fff'
      }
    },
    series: [
      {
        name: '地区分布',
        type: 'map',
        map: 'china',
        roam: true,
        emphasis: {
          label: {
            show: true
          }
        },
        data: [
          { name: '北京', value: 1000 },
          { name: '上海', value: 800 },
          { name: '广东', value: 900 },
          { name: '江苏', value: 700 },
          { name: '浙江', value: 600 }
        ],
        itemStyle: {
          areaColor: '#2f89cf',
          borderColor: '#fff',
          borderWidth: 1
        }
      }
    ]
  }
  chart.setOption(option)
  return chart
}

export function initGoodChart(el) {
  const chart = echarts.init(el)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      textStyle: {
        color: '#fff'
      }
    },
    series: [
      {
        name: '商品分类',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold',
            color: '#fff'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 1048, name: '服装' },
          { value: 735, name: '电子' },
          { value: 580, name: '食品' },
          { value: 484, name: '家居' },
          { value: 300, name: '其他' }
        ]
      }
    ]
  }
  chart.setOption(option)
  return chart
}

export function initOrderChart(el) {
  const chart = echarts.init(el)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['已完成', '处理中', '已取消'],
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      }
    },
    series: [
      {
        name: '已完成',
        type: 'bar',
        stack: 'total',
        data: [320, 302, 301, 334, 390, 330, 320],
        itemStyle: {
          color: '#2f89cf'
        }
      },
      {
        name: '处理中',
        type: 'bar',
        stack: 'total',
        data: [120, 132, 101, 134, 90, 230, 210],
        itemStyle: {
          color: '#00f2f1'
        }
      },
      {
        name: '已取消',
        type: 'bar',
        stack: 'total',
        data: [20, 32, 21, 34, 30, 30, 20],
        itemStyle: {
          color: '#ff9f7f'
        }
      }
    ]
  }
  chart.setOption(option)
  return chart
}

export function initCouponChart(el) {
  const chart = echarts.init(el)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['已使用', '未使用', '已过期'],
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      }
    },
    series: [
      {
        name: '已使用',
        type: 'line',
        stack: 'Total',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(47,137,207,0.3)'
            }, {
              offset: 0.8,
              color: 'rgba(47,137,207,0)'
            }],
            global: false
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330]
      },
      {
        name: '未使用',
        type: 'line',
        stack: 'Total',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(0,242,241,0.3)'
            }, {
              offset: 0.8,
              color: 'rgba(0,242,241,0)'
            }],
            global: false
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: [220, 182, 191, 234, 290, 330, 310, 282, 291, 334, 390, 430]
      },
      {
        name: '已过期',
        type: 'line',
        stack: 'Total',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(255,159,127,0.3)'
            }, {
              offset: 0.8,
              color: 'rgba(255,159,127,0)'
            }],
            global: false
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: [150, 232, 201, 154, 190, 330, 410, 382, 391, 434, 490, 530]
      }
    ]
  }
  chart.setOption(option)
  return chart
}

export function useCharts() {
  const charts = []
  const eventHandlers = new Map()

  const initChart = (el, type) => {
    let chart
    switch(type) {
      case 'trade':
        chart = initTradeChart(el)
        break
      case 'member':
        chart = initMemberChart(el)
        break
      case 'map':
        chart = initMapChart(el)
        break
      case 'good':
        chart = initGoodChart(el)
        break
      case 'order':
        chart = initOrderChart(el)
        break
      case 'coupon':
        chart = initCouponChart(el)
        break
    }
    if (chart) {
      charts.push(chart)
      // 添加事件监听
      addChartEvents(chart, type)
    }
    return chart
  }

  const addChartEvents = (chart, type) => {
    if (type === 'map') {
      chart.on('click', (params) => {
        emitEvent(ChartEventType.REGION_SELECT, {
          region: params.name,
          value: params.value
        })
      })
    }

    // 为所有图表添加时间轴事件
    chart.on('timelinechanged', (params) => {
      emitEvent(ChartEventType.TIME_RANGE_CHANGE, {
        timeRange: params.currentIndex
      })
    })
  }

  const on = (eventType, handler) => {
    if (!eventHandlers.has(eventType)) {
      eventHandlers.set(eventType, [])
    }
    eventHandlers.get(eventType).push(handler)
  }

  const off = (eventType, handler) => {
    if (eventHandlers.has(eventType)) {
      const handlers = eventHandlers.get(eventType)
      const index = handlers.indexOf(handler)
      if (index > -1) {
        handlers.splice(index, 1)
      }
    }
  }

  const emitEvent = (eventType, data) => {
    if (eventHandlers.has(eventType)) {
      eventHandlers.get(eventType).forEach(handler => handler(data))
    }
  }

  const updateChartData = (chart, type, data) => {
    if (!chart) return

    switch(type) {
      case 'trade':
        chart.setOption({
          series: [{
            data: data
          }]
        })
        break
      case 'member':
        chart.setOption({
          series: [{
            data: data
          }]
        })
        break
      case 'map':
        chart.setOption({
          series: [{
            data: data
          }]
        })
        break
      case 'good':
        chart.setOption({
          series: [{
            data: data
          }]
        })
        break
      case 'order':
        chart.setOption({
          series: [
            { data: data.completed },
            { data: data.processing },
            { data: data.cancelled }
          ]
        })
        break
      case 'coupon':
        chart.setOption({
          series: [
            { data: data.used },
            { data: data.unused },
            { data: data.expired }
          ]
        })
        break
    }
  }

  const resizeCharts = () => {
    charts.forEach(chart => chart.resize())
  }

  const destroyCharts = () => {
    charts.forEach(chart => chart.dispose())
    charts.length = 0
    eventHandlers.clear()
  }

  return {
    initChart,
    updateChartData,
    resizeCharts,
    destroyCharts,
    on,
    off,
    ChartEventType
  }
} 